package cn.hist.hfp.controller;

import cn.hist.hfp.RoleType;
import cn.hist.hfp.entity.Reservation;
import cn.hist.hfp.entity.User;
import cn.hist.hfp.service.UserService;
import cn.hist.hfp.util.Authentication;
import cn.hist.hfp.util.MyResponse;
import cn.hist.hfp.vo.ReservationVO;
import cn.hist.hfp.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    private final
    UserService userService;

    private final
    Authentication authentication;

    @Autowired
    public UserController(UserService userService, Authentication authentication) {
        this.userService = userService;
        this.authentication = authentication;
    }

    @PostMapping
    public int create(@RequestBody User user) {
        return userService.create(user).getId();
    }

    @GetMapping("/{id}")
    public UserVO findOne(@PathVariable int id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.USER, RoleType.MANAGER);
        return userService.findOneVO(id);
    }

    @GetMapping("/check")
    public int checkLoginName(@RequestParam String loginName) {
        return userService.checkLoginName(loginName);
    }

    @PutMapping
    public UserVO update(@RequestBody User user, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return userService.updateVO(user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Integer> delete(@PathVariable int id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.MANAGER);
        return new MyResponse<Integer>().response(200, authentication.refreshToken(token), userService.delete(id));
    }

    @PostMapping("/reservation")
    public ResponseEntity<Integer> addReservation(@RequestBody Reservation reservation, @RequestHeader String token) {
        return new MyResponse<Integer>().response(200, authentication.refreshToken(token), userService.createReservation(reservation));
    }

    @DeleteMapping("/reservation/{id}")
    public ResponseEntity<Integer> deleteReservation(@PathVariable int id, @RequestHeader String token) {
        return new MyResponse<Integer>().response(200, authentication.refreshToken(token), userService.deleteReservation(id));
    }

    @GetMapping("/reservation/{id}")
    public List<ReservationVO> findAllReservations(@PathVariable int id) {
        return userService.findAllReservations(id);
    }
}
